/**
 * 2018年12月5日下午12:13:54
 * @author 谢进财
 */
package com.baihang.project.ds.service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baihang.framework.dao.Record;
import com.baihang.framework.kit.DateKit;
import com.baihang.framework.kit.ExcelKit;
import com.baihang.framework.kit.JsonKit;
import com.baihang.framework.kit.PathKit;
import com.baihang.framework.kit.StrKit;
import com.baihang.framework.service.BaseService;
import com.baihang.project.ds.dao.RoomMonitorDao;

import net.sf.json.JSONArray;

/**
 * @author 
 *
 */
@Service
public class RoomMonitorService extends BaseService {
	private static Logger logger = LoggerFactory.getLogger(RoomMonitorService.class);
	@Autowired
	private RoomMonitorDao dao;
	
	public String formByTel(String tel) {
		String result="false";
		String msg="0";
		Record rec = dao.queryForRecord(String.format("select D_Name as name,D_Card as dcardno,D_ID as dclientid from t_user where D_Tel=%s", tel));
		if(rec!=null) {
			result ="true";
			msg =JsonKit.toJson(rec);
		}
		return JsonKit.toDoubleJson2(result, msg);
	}
	@Transactional
	public boolean RoomGuideAjax(String action,String name,String tel,String cardno,int roomid) {
		if("setroomorder".equals(action)) {//预定
			String operationRemark =String.format("H管理:/%s", DateKit.getCurrentDate(DateKit.Format_DateTime));
			if(StrKit.isEmpty(tel)) {//空绑定,房源只改变销控状态，不与认筹用户绑定
				dao.update(String.format("update room set D_Monitor=1,D_OperationRemark='%s' where D_ID=%d",operationRemark, roomid));
			}else {
				dao.update(String.format("update room set D_Monitor=1,D_Operation=%s,D_OperationRemark='%s' where D_ID=%d", tel,operationRemark,roomid));
			}
		}else if("roomunorder".equals(action)) {//取消预定
			dao.update(String.format("update room set D_Monitor=0,D_Operation=null,D_OperationRemark=null where D_ID=%d", roomid));
		}else if("setroomunred".equals(action)) {//退订
			dao.update(String.format("update room set D_Monitor=0,D_Operation=null,D_OperationRemark=null where D_ID=%d", roomid));
		}
		return true;
	}
	
	public boolean RoomGuideAjaxAll(String json) {
		JSONArray jsonArray = JSONArray.fromObject(json); 
		try {
			dao.batchUpdateRoomGuideList(jsonArray);
		}catch (Exception e) {
			logger.info(e.getMessage());
			return false;
		}
		return true;
	}
	public String readRoomBackOrderByExcel(String fileName) {
		String filePath = PathKit.getWebRootPath()+"/upload/"+fileName;
		System.err.println(filePath);
		File file = new File(filePath);
		 Map<Integer,String> keyMap = new HashMap<Integer,String>();			
		 keyMap.put(0, "name");
		 keyMap.put(1, "tel");
		 keyMap.put(2, "cardno");
		 keyMap.put(3, "roomid");		
		 List<Record> recList = new ArrayList<Record>();
		try {
			recList = ExcelKit.readFromExcel(file,keyMap);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/*for(Record rec:recList) {
			rec.getColumns().put("D_BanName", fileName.substring(0, fileName.indexOf(".")));
		}*/
		 String json =JsonKit.listToJson(recList, 1);
		 //System.err.println(json);
		return json;
	}
	
	public void singleFanHong(int id) {
		Random random = new Random();
		//long bianlan = random.nextInt(10);
		Record rec= dao.queryForRecord(String.format("select D_OperationRemark from room where D_ID=%d",id));

		long bianhong = random.nextInt(30);
		ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
                new BasicThreadFactory.Builder().namingPattern("socket-schedule-pool-%d").daemon(true).build());
          
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                    	 try {							
								/*TimeUnit.SECONDS.sleep(bianlan);
								System.err.println(bianlan+"线程操作");*/
								dao.update(String.format("update room set D_Monitor=2 where D_ID=%d",id));
								TimeUnit.SECONDS.sleep(bianhong);
								System.err.println(bianhong+"线程操作");
								String operationRemark =String.format("%s|S管理:/%s",rec.getStr("D_OperationRemark"), DateKit.getCurrentDate(DateKit.Format_DateTime));
								dao.update(String.format("update room set D_Monitor=3,D_OperationRemark='%s' where D_ID=%d",operationRemark,id)); 
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} 
                    }
                });
	}
	public String moreFanHong() {
		Random random = new Random();
		//查出所有被预定状态的房源
		List<Record> roomIdlist= dao.queryForRecordList("select D_ID,D_OperationRemark from room where D_Monitor=1");
		if(roomIdlist!=null && roomIdlist.size()>0) {
			ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
					new BasicThreadFactory.Builder().namingPattern("socket-schedule-pool-%d").daemon(true).build());
			for(Record rec:roomIdlist) {
				//long bianlan = random.nextInt(10);
				dao.update(String.format("update room set D_Monitor=2 where D_ID=%d",rec.getInt("id")));
				
				long bianhong = random.nextInt(30);				
				executorService.schedule(new Runnable() {
					@Override
					public void run() {
						/*TimeUnit.SECONDS.sleep(bianlan);
						System.err.println(String.format("%d号房间在%d秒被翻蓝", rec.getInt("D_ID"),bianlan));*/
						logger.info(String.format("%d号房间在%d秒被翻红", rec.getInt("id"),bianhong));
						String operationRemark =String.format("%s|S管理:/%s",rec.getStr("D_OperationRemark"), DateKit.getCurrentDate(DateKit.Format_DateTime));
						dao.update(String.format("update room set D_Monitor=3,D_OperationRemark='%s' where D_ID=%d",operationRemark,rec.getInt("id"))); 
					}
				},bianhong,TimeUnit.SECONDS);
			}
			executorService.shutdown();
			return JsonKit.listToJson(roomIdlist, 1);
		}else {
			return "0";
		}
	}
	
	public boolean moreReset() {
		
		int result = dao.update("update room set D_Monitor=0,D_Operation=null,D_OperationRemark=null");
		if(result>0) {
			return true;
		}
		return false;
	}
	public String checkRoomState() {
		
		List<Record>  list = dao.queryForRecordList("select D_ID ,D_state ,D_CollectionCount ,D_Monitor from room");
		String json = JsonKit.listToJson(list, 1);	
		return JsonKit.toDoubleJson2("true", json);
	}
}
